package colaborativo.ondefica;

import org.json.JSONArray;
import org.json.JSONException;
import org.osmdroid.api.IMapController;
import org.osmdroid.bonuspack.overlays.Marker;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.Overlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.CheckBox;
import android.widget.EditText;

public class IncludePoint extends Activity {
	MapView map;
	protected long tp_prs;
	String nome;
	int mLoads = 0;
	int X ,Y ;
	CheckBox chk;
	Boolean mod=false; 
	Overlay marcado;
	protected long ini_prs;
	protected int posX;
	protected int posY;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_include_point);			
		
		map = (MapView) findViewById(R.id.map);
		map.setTileSource(TileSourceFactory.MAPNIK);
		map.setBuiltInZoomControls(true);
		map.setMultiTouchControls(true);
		GeoPoint startPoint;
		
		Intent it = getIntent();
		Bundle extras = it.getExtras();
		if(extras!=null){
			Log.d("IP.Debug", extras.getDouble("xcenter")+"##############################"+extras.getDouble("ycenter"));
			startPoint = new GeoPoint(extras.getDouble("xcenter"),extras.getDouble("ycenter"));
		}else{
			startPoint = new GeoPoint(-3.08923,-59.96453);
		}
		IMapController mapController = map.getController();
		mapController.setZoom(18);
		mapController.setCenter(startPoint);								
		
		map.setOnTouchListener(new OnTouchListener() {			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				Boolean control = true;			
				X = (int)event.getX();          
	            Y = (int)event.getY();
	            
				switch (event.getAction() & MotionEvent.ACTION_MASK) {
				    case MotionEvent.ACTION_DOWN:				    	
				        v.setPressed(true);					        
				        Log.d("IP.Debug", "entra1,5s");
			        	AlertDialog.Builder alert = new AlertDialog.Builder(IncludePoint.this);

			            alert.setTitle("LOCAL");
			            alert.setMessage("Insira o nome do Local marcado:");

			            // Set an EditText view to get user input 
			            final EditText input = new EditText(IncludePoint.this);
			            alert.setView(input);

			            alert.setPositiveButton("Cadastrar", new DialogInterface.OnClickListener() {
			            public void onClick(DialogInterface dialog, int whichButton) {
			              Editable value = input.getText();
			              nome = value.toString();			              			             
			              				            				            				            					            					            
				            Log.d("IP.Debug.ValueNome", nome.toString());
				            if(nome!=null){
					            
					        	if(marcado!=null)
					        		map.getOverlays().remove(marcado);
					        	
					        	Drawable poiIcon = getResources().getDrawable(R.drawable.marker_node);				        	
					            GeoPoint gPoint = (GeoPoint) map.getProjection().fromPixels(X, Y);
					            
					            Log.d("iP.Marcar.Debug", gPoint.toString()+nome);
					            Marker startMarker = new Marker(map);
					            startMarker.setPosition(gPoint);
					            startMarker.setAnchor(Marker.ANCHOR_CENTER, 1.0f);
					            startMarker.setIcon(poiIcon);
					            startMarker.setTitle(nome);
					            marcado = startMarker;
					            map.getOverlays().add(marcado);
					            map.invalidate();
					            posX = gPoint.getLatitudeE6();
					            posY = gPoint.getLongitudeE6();
				            }
			            }
			            });
			            alert.show();
				        break;
				    case MotionEvent.ACTION_UP:				    	
				    	control=false;
				    	break;
				    case MotionEvent.ACTION_OUTSIDE:				    	
				    	v.setPressed(false);
				    	control=false;				       	        				        
				       				   
			    }
				
				return control;
			}
		});						
	}	

	public void salvarLugar(View v){
		Log.d("iP.SALVAR.Debug", "gogog");
		new MyAsyncInsert().execute("asrgh");					
	}		
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.include_point, menu);
		return true;
	}	 
	 	 
	 private class MyAsyncInsert extends AsyncTask<String, Integer, JSONArray>{
	    	@Override
	        protected JSONArray doInBackground(String... params) {	        		        	
	        	
	    		String qry= "INSERT INTO `geoPonto`(`nomeLocal`, `latitute`, `longitude`, `idLocal`) VALUES ('"+nome+"',"+posX+","+posY+",NULL)";
	    		Log.d("oM.Ip.Query", qry);	    		
	    		return DbConnection.consulta(qry);	    				        
	        }
	         
	        protected void onPostExecute(JSONArray result){
//		        Log.d("oM.pV.resultado", jSarr.toString());	    		
	        	
	        	Log.d("oM.Ip.InserirResult", "Acabou consulta ||"+result.toString());	    			        	
	    		if(result!=null)
	    			new MyAsyncID().execute("aiaiai");
	        }
	        protected void onProgressUpdate(Integer... progress){
//	        	progress(progress[0]);
	        }
	        
	        
	    }
	 
	 private class MyAsyncID extends AsyncTask<String, Integer, JSONArray>{
	    	@Override
	        protected JSONArray doInBackground(String... params) {	        		        	
	        	
	    		String qry= "SELECT * FROM `geoPonto`";
	    		Log.d("oM.iD.Query", qry);	    		
	    		return DbConnection.consulta(qry);	    				        
	        }
	         
	        protected void onPostExecute(JSONArray result){
//		        Log.d("oM.pV.resultado", jSarr.toString());	    		
	        	
	        	Log.d("oM.Ip.Result", "Acabou id consulta");	    			        	
	    		if(result!=null){
	    			Intent intent = new Intent(IncludePoint.this, SelectPoint.class);	    			
	    			try {	    				
						intent.putExtra("id", result.getJSONObject(result.length()-1).getInt("idLocal"));
						Log.d("iP.id.Debug", result.getJSONObject(result.length()-1).getString("idLocal"));
					} catch (JSONException e) {					
						e.printStackTrace();
					}
	    			intent.putExtra("nomeLocal", nome);
	    			setResult(Activity.RESULT_OK, intent);
	    			finish();
	    		}
	        }
	        protected void onProgressUpdate(Integer... progress){
//	        	progress(progress[0]);
	        }
	        
	        
	    }
}
